<?php
/**
 * Created by PhpStorm.
 * User: khq
 * Date: 17-3-1
 * Time: 下午3:23
 */

namespace Warehouse\Service;


use Inbound\Service\PrepareneedsService;
use Inbound\Service\PublicInfoService;
use Think\Exception;
use Warehouse\Model\BadProductsModel;
use Warehouse\Model\UnqualifiedDealInvoicesModel;

class BadProductsService
{
    public $dealInvoices    = NULL;

    public $badProducts     = NULL;

    public $wasterReceipts  = NULL;

    public $puDetails       = NULL;
    
    public $stockIn         = NULL;
    //查询记录总数
    public $count           = NULL;
    //页面展示包含页面样式
    public $page            = NULL;
    //数据
    public $data            = array();
    //当前时间
    public $time            = NULL;

    /*
     * 构造函数初始化
     * */
    public function __construct($table = '',$param=array())
    {
        $this->dealInvoices = D('UnqualifiedDealInvoices','Model');
        $this->wasterReceipts=D('WasterReceipts','Model');
        $this->badProducts  = D('BadProducts','Model');
        $this->puDetails    = D('PurchaseOrderDetails','Model');
        $this->stockIn      = D('StockIn','Model');
        $this->time         = date('Y-m-d H:i:s',time());
    }

    /**
     * @param array $_array
     * @param bool $flag
     * @return mixed
     * 查询不良品出库单
     * 作者:khq 2017.3.15
     */
    public function bad_products_detail($_array = array(),$flag = TRUE) {
        $badProdcuts   = $this->get_badProducts_model($_array);
        $badProdcuts_count = clone $badProdcuts;

        if($flag)
        {
            $this->count= $badProdcuts_count->count();             //数量

            $Page = new \Org\Util\Page($this->count,20);           //实例化分页类 传入总记录数和每页显示的记录数(15)

            $this->page = $Page->show();                           // 分页显示输出

            $badProdcuts->order("id")
                ->limit($Page->firstRow.','.$Page->listRows);
        }
        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $result = $badProdcuts->select();
        $result = $this->format_badProdcuts_data($result);
        $result = $this->get_badPorducts_detail($result);          //添加上不良品出库信息
        return $result;
    }
    /**
     * 查询不良品入库单
     * khq 2017.3.2
     */
    public function select_unqualified_detail($_array = array(),$flag = TRUE)
    {

        $dealInvoices   = $this->get_unqualified_deal_model($_array);
        $dealInvoices_count = clone $dealInvoices;

        if($flag)
        {
            $this->count= $dealInvoices_count->count();            //数量

            $Page = new \Org\Util\Page($this->count,20);           //实例化分页类 传入总记录数和每页显示的记录数(15)

            $this->page = $Page->show();                           // 分页显示输出

            $dealInvoices->order("id")
                ->limit($Page->firstRow.','.$Page->listRows);
        }

        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $result = $dealInvoices->select();
        $result = $this->format_dealInvoices_data($result);
        return $result;
    }

    /**
     * @param $data
     * @return mixed
     * 格式化不良品出库单信息
     * 作者:khq 2017.3.15
     */
    public function format_badProdcuts_data($data) {
        $status_arr = PublicdataService::get_bad_products_status();
        $way_arr    = PublicdataService::unqualified_deal_way();
        $site_arr   = PublicInfoService::get_site_array();
        foreach($data as &$_data)
        {
            $_data['status']        = $status_arr[$_data['status']];
            $_data['supplier']      =PublicdataService::get_supplier_name($_data['supplier']);
            $_data['purchase_man']  = PublicdataService::get_user_name($_data['purchase_man']);
            $_data['operate_man']   = PublicdataService::get_user_name($_data['operate_man']);
            $_data['check_man']     = PublicdataService::get_user_name($_data['check_man']);
            $_data['fail_deal_way'] = $way_arr[$_data['fail_deal_way']];
            $_data['site_id']     = $site_arr[$_data['site_id']];
        }
        return $data;
    }

    /**
     * @return int
     * 不良品实物确认处理
     * khq 2017.3.16
     */
    public function confirm_bad_product() {
        $id = $this->update_bad_product($_GET);                           //更新不良品出库单
        $bad_product = $this->badProducts->bad_product_data($_GET['id']); //获取不良品出库单信息
        $purchase_detail = $this->puDetails
                ->get_purchaseorder_detail(array('purchaseorder_id'=>$bad_product['purchaseorder_id'],
                    'sku'=>$bad_product['sku']));                         //采购明细
        switch ($bad_product['fail_deal_way']) {
            case 5:                                                       //让步接收
                /** 1.创建入库单 */
                $win[] = array(
                    'warehouse_date'              => date('Y-m-d',$this->time),
                    'op_time'                     => date('Y-m-d'),
                    'unqualified_deal_invoice_id' => $bad_product['unqualified_id'], //不合格处理表的id
                    'purchaseorders_id'           => $bad_product['purchaseorder_id'],
                    'supplier_id'                 => $bad_product['supplier'],
                    'sku'                         => $bad_product['sku'],
                    'sku_name'                    => $bad_product['sku_name'],
                    'sku_standard'                => $bad_product['sku_standard'],
                    'storage_position'            => $bad_product['storage_position'],
                    'warehouse_quantity'          => $bad_product['quantity'],
                    'available_quantity'          => $bad_product['quantity'],
                    'single_price'                => $bad_product['coupon_price'],  //本次费用单价
                    'money'                       => $bad_product['quantity']*$bad_product['coupon_price'],
                    'tax_price'                   => 0,
                    'type'                        => 10,                            //正常采购入库
                    'warehouse_man'               => $_SESSION['current_account']['role_id'],
                );
                if($bad_product['purchaseorder_id']){
                    $win['purchaseorder_id'] = $bad_product['purchaseorder_id'];
                    $win['remark'] = "采购折让入库，".$bad_product['purchaseorder_id'];
                }
                $stock_data = D('StockIn', 'Model')->batch_create($win);
                if(!$stock_data || empty($stock_data)) {
                    $this->badProducts->model->rollback();
                    return 402;   //让步接收时,创建入库单失败
                }
                /** 2.创建质检明细单 */
                //获取原质检明细信息
                $check_old =
                    D('CheckQualityDetails','Model')->check_detail_by_id($bad_product['check_detail_id']);
                $check_datas = array(
                    'invoice_date' => $this->time,
                    'check_man'    => $_SESSION['current_account']['role_id'],
                    'purchaseorder_id' => $check_old['purchaseorder_id'],
                    'recieve_detail_id'=> $check_old['recieve_detail_id'],
                    'supplier_id' => $check_old['supplier_id'],
                    'sku' => $check_old['sku'],
                    'sku_name' => $check_old['sku_name'],
                    'sku_standard' => $check_old['sku_standard'],
                    'storage_position' => $check_old['storage_position'],
                    'qualified_quantity' => $bad_product['quantity'],
                    'check_quantity'    => $bad_product['quantity'],
                    'fail_deal_way' => 5
                );
                D('CheckQualityDetails','Model')->add_check_quality_details(
                    $check_datas,$this->badProducts->_db);
                /** 3.更新采购明细不良品数量 */
                $pu_data = array(
                    'return_quantity' => $purchase_detail['return_quantity']-$bad_product['quantity'],//不良品数量
                );
                $this->puDetails->update_purchaseorder_details(
                    array('id'=>$purchase_detail['id']),$pu_data,$this->badProducts->_db);
                /** 4.判断sku库存表是否有期初,么有则增加期初 */
                $inventory_map = array(
                    'sku' => $bad_product['sku'],
                    'inventory_date' => date('Y-m-01', time()),
                    'export_tax_rebate'=> $bad_product['export_tax_rebate']
                );
                $inventory_num = D('Inventories','Model')->get_sku_count($inventory_map);
                if(!$inventory_num) {
                    $inventory_data[] = array(
                        'inventory_date' => date('Y-m-01', time()),
                        'sku'            => $bad_product['sku'],
                        'sku_name'       => $bad_product['sku_name'],
                        'sku_standard'   => $bad_product['sku_standard'],
                        'storage_position' => $bad_product['storage_position'],
                        'supplier_id'    => $bad_product['supplier'],
                        'quantity'       => $bad_product['quantity'],
                        'cost'           => 0
                    );
                    $inventory_id = D('Inventories','Model')->addall_data($inventory_data); //创建期初库存数据
                }
                /** 5.回写采购明细入库数量 更新采购明细状态,采购单状态 */
                //回写采购单明细的数据
                $warehouse_quantity = M( 'purchaseorder_details', 'wms_', $this->badProducts->_db )
                    ->where(
                        array(
                            'purchaseorder_id' => $bad_product['purchaseorder_id'],
                            'sku'              => $bad_product['sku']
                        )
                    )
                    ->getfield( 'ware_quantity' );
                $this->update(
                    array(
                        'purchaseorder_id' => $bad_product['purchaseorder_id'],
                        'sku'              => $bad_product['sku']
                    ), array(
                    'ware_quantity' => $bad_product['quantity'] + $warehouse_quantity
                ),
                    M( 'purchaseorder_details', 'wms_', $this->badProducts->_db )
                );
                //回写采购单和明细的状态;
                $this->stockIn->update_order_status( 
                    $bad_product, M( 'purchaseorder_details', 'wms_', $this->badProducts->_db ) );
                break;
            case 3:                                                       //报废
                $price = array();
                if($bad_product['check_detail_id'])
                    $price = $this->get_sku_money_cost($purchase_detail,$bad_product['quantity']);
                $array = array(
                    'sku'                 =>$bad_product['sku'],
                    'sku_name'            =>$bad_product['sku_name'],
                    'sku_standard'        =>$bad_product['sku_standard'],
                    'storage_position'    =>$bad_product['storage_position'],
                    'quantity'            =>$bad_product['quantity'],
                    'single_price'        =>$price['single_price']?$price['single_price']:0,
                    'money'               =>$price['money'],
                    'cost'                =>$price['cost'],
                    'table_id'            =>$bad_product['id'],
                    'remark'              =>"不良品报废处理，报废出库单号是".$bad_product['id'],
                    'waster_receipts_time'=>$this->time
                );
                $wasterReceiptsId = $this->wasterReceipts->create($array);
                if($wasterReceiptsId){
                    return 200;
                }
                break;
            default:                                                      //其它
                if($id){
                    return 200;
                }
                break;
        }
        $this->badProducts->model->commit();
        return 200;
    }

    /**
     * @param $purchase_detail
     * @param $num
     * @return array
     * 计算不同税模式的金额和成本
     * khq 2017.3.16
     */
    public function get_sku_money_cost($purchase_detail,$num) {

        $tax_way = $purchase_detail['tax_way'];                                               //计税方式
        $single_price = $purchase_detail['single_price'];                                     //单价
        $tax_rate = $purchase_detail['tax_rate']; //税率
        $re = array();
        if($tax_way==0){                                                                      //不计税时，成本=金额；税额=0
            $re['single_price'] = $single_price; //单价
            $re['money'] =$single_price*$num;  //金额
            $re['cost'] = $re['money']; //成本
            $re['tax_price'] = 0;
        }else if($tax_way==-1){                                                               //加内税的计算成本和税额
            $re['single_price'] = $single_price;
            $re['money'] =$single_price*$num;
            $re['cost'] = ($single_price*$num)/(1+$tax_rate);
            $re['tax_price'] = $re['cost']*$tax_rate;
        }else if($tax_way==1){                                                                //加外税时的计算成本和税额
            $re['single_price'] = $single_price;
            $re['money'] =($single_price*$num)*(1+$tax_rate);
            $re['cost'] = $single_price*$num;
            $re['tax_price'] = $re['cost']*$tax_rate;
        }
        return $re;
    }

    /**
     * @param $_GET
     * @return mixed
     * 更新不良品状态信息
     * khq 2017.3.15
     */
    public function update_bad_product($_arr) {
        $param = array(
            'warehouse_remark' => mysql_escape_string($_arr['warehouse_remark']),
            'warehouse_man'    => $_SESSION['current_account']['id'],
            'status'           => 20,
            'out_time'         => $this->time,
        );
        $array = array('id'=>trim($_GET['id']));
        return $this->badProducts->update($array,$param,$this->badProducts->_db);
    }
    /**
     * @param $data
     * @return mixed
     * 格式化
     */
    public function format_dealInvoices_data($data)
    {
        //格式化
        $status_arr = PublicdataService::get_bad_products_status();
        $site_arr   = PublicInfoService::get_site_array();
        foreach($data as &$_data) {
            $_data['status']      = $status_arr[$_data['status']];
            $_data['supplier']    =PublicdataService::get_supplier_name($_data['supplier']);
            $_data['purchase_man']= PublicdataService::get_user_name($_data['purchase_man']);
            $_data['operate_man'] = $_data['operate_man']?PublicdataService::get_user_name($_data['operate_man']):'无';
            $_data['quality_man'] = PublicdataService::get_user_name($_data['quality_man']);
            $_data['export_tax_rebate'] = $_data['export_tax_rebate']==1?'出口退税':'非出口退税';
            $_data['site_id']           = $site_arr[$_data['site_id']];
        }
        return $data;
    }

    /**
     * 根据不良品入库id获取不良品出库信息
     * khq 2017.3.6
     */
    public function get_badPorducts_detail(&$datas)
    {
        foreach ($datas as $k=>$v){
            $bad_products = $this->badProducts->get_bad_product_delivery_byid($v['id']);
            $datas[$k]['bad_products'] = $bad_products;
        }
        return $datas;
    }

    /**
     * @param $_array
     * @return mixed
     * 获取不良品入库单model
     * khq 2017.3.21
     */
    public function get_unqualified_deal_model(&$_array)
    {
        $model = M('unqualified_deal_invoices','wms_','fbawarehouse');

        if($_array)
            $_array = array_filter($_array);
        $_array = PrepareneedsService::trim_array($_array);

        foreach($_array as $key=>$_arr) {
            switch($key){
                case 'check_time_from':
                    $_array['check_time'][] = array('egt',$_arr);
                    unset($_array['check_time_from']);
                    break;
                case 'check_time_to':
                    $_array['check_time'][] = array('elt',$_arr);
                    unset($_array['check_time_to']);
                    break;
            }
        }
        if($_array['supplier']) {
            $_array['supplier']=PublicdataService::get_supplier_id($_array['supplier']);
        }
        if($_array['purchase_man']) {
            $_array['purchase_man']=PublicdataService::get_user_id($_array['purchase_man']);
        }
        return $model -> where($_array);
    }
    /**
     * @param $_array
     * @return mixed
     * 获取不良品出库单model对象
     * 作者:khq 2017.3.15
     */
    public function get_badProducts_model(&$_array)
    {
        if($_array)
            $_array = array_filter($_array);
        foreach($_array as $key=>$_arr) {
            switch($key){
                case 'deal_time_from':
                    $_array['deal_time'][] = array('egt',$_arr);
                    unset($_array['deal_time_from']);
                    break;
                case 'deal_time_to':
                    $_array['deal_time'][] = array('elt',$_arr);
                    unset($_array['deal_time_to']);
                    break;
            }
        }
        if($_array['deal_time']) {
            $_array['wms_bad_product_delivery.deal_time']=$_array['deal_time'];
            unset($_array['deal_time']);
        }
        if($_array['purchaseorder_id']) {
            $_array['wms_bad_product_delivery.purchaseorder_id']=$_array['purchaseorder_id'];
            unset($_array['purchaseorder_id']);
        }
        if($_array['supplier']) {
            $_array['wms_bad_product_delivery.supplier']=PublicdataService::get_supplier_id($_array['supplier']);
            unset($_array['supplier']);
        }
        if($_array['sku']) {
            $_array['wms_bad_product_delivery.sku']=$_array['sku'];
            unset($_array['sku']);
        }
        if($_array['purchase_man']) {
            $_array['wms_bad_product_delivery.purchase_man']=PublicdataService::get_user_id($_array['purchase_man']);
            unset($_array['purchase_man']);
        }
        if($_array['fail_deal_way']) {
            $_array['wms_bad_product_delivery.fail_deal_way']=$_array['fail_deal_way'];
            unset($_array['fail_deal_way']);
        }
        if($_array['id']) {
            $_array['wms_bad_product_delivery.id']=$_array['id'];
            unset($_array['id']);
        }
        if($_array['site_id']) {
            $_array['wms_bad_product_delivery.site_id'] = $_array['site_id'];
            unset($_array['site_id']);
        }
        return $this->badProducts->bad_products_and_check_detail_model($_array);
    }
    /**
     * @param array $_array
     * @return mixed
     * ajax获取不良品入库单
     * khq 2017.3.2
     */
    public function ajax_select_detail($_array = array())
    {
        $dealInvoices   = $this->get_unqualified_deal_model($_array);

        $result       = $dealInvoices->find();
        return $result;
    }
    /**
     * 编辑不良品入库单不合格原因
     * khq 2017.3.2
     */
    public function ajax_edit()
    {
        $data = array(
            'quality_remark'    => mysql_escape_string(trim($_GET['quality_remark']))
        );
        try{
            $this->dealInvoices->update(array('id'=>$_GET['id']),$data);
            $this->dealInvoices->model->commit();
            return 200;
        }catch (Exception $e){
            $this->dealInvoices->model->rollback();
            print $e->getMessage();
            return 402;
        }

    }

    /**
     * 导出不良品入库单
     * khq 2017.3.2
     */
    public function download_bad_products()
    {
        $detail_data = $this->select_unqualified_detail($_GET,false);
        set_time_limit(0);
        ini_set('memory_limit','1024M');

        //为fputcsv()函数打开文件句柄
        $output = fopen('php://output', 'w') or die("can't open php://output");
        //告诉浏览器这个是一个csv文件
        $fileName = "不良品查询修改报表(".date('Ymd',time()).")";

        header("Content-Type: application/csv");
        header("Content-Disposition: attachment; filename=$fileName.csv");
        //输出表头
        $table_head = array(
            '采购单号','质检单号','SKU','中文名称','退税类型','站点','供应商', '不合格量', '质检时间', '采购员', 
            '质检不合格原因','状态','处理时间'
        );
        fputcsv($output, $table_head);
        //输出每一行数据到文件中
        foreach ($detail_data as $info) {
            $data_arr = array(
                'purchaseorder_id' => $info['purchaseorder_id'],
                'check_detail_id'  => $info['check_detail_id'],
                'sku'              => $info['sku'],
                'sku_name'         => $info['sku_name'],
                'export_tax_rebate'=> $info['export_tax_rebate'],
                'site_id'          => $info['site_id'],
                'supplier'         => $info['supplier'],
                'quantity'         => $info['quantity'],
                'check_time'       => $info['check_time'],
                'purchase_man'     => $info['purchase_man'],
                'quality_remark'   => $info['quality_remark'],
                'status'           => $info['status'],
                'deal_time'           => $info['deal_time']
            );
            fputcsv($output, array_values($data_arr));
            unset($data_arr);
        }
        //关闭文件句柄
        fclose($output) or die("can't close php://output");
        exit;
    }

    /**
     * @return int
     * 检查不良品处理数据合法性
     * khq 2017.3.7
     */
    public function check_deal()
    {
        $id              = trim($_POST['id']);
        $quantity = $this->dealInvoices->get_purchase_man_by_param($id,'quantity');
        $quantity_arr    = explode(';',rtrim($_POST['quantity'],';'));                 //数量
        $quantity_sum    = 0;
        foreach ($quantity_arr as $k=>$v){
            $quantity_sum += $v;
        }
        if($quantity_sum>$quantity) return 401;
    }
    /**
     * 不良品处理
     * khq 2017.3.6
     */
    public function deal()
    {
        $id              = trim($_POST['id']);
        $purchase_man    = $this->dealInvoices->get_purchase_man_by_param($id,'purchase_man');
        $quantity_arr    = explode(';',rtrim($_POST['quantity'],';'));                 //数量
        $way_arr         = explode(';',rtrim($_POST['way'],';'));                      //处理方式
        $remark_arr      = explode(';',rtrim($_POST['remark'],';'));                   //采购处理备注
        $return_cost_arr = explode(';',rtrim($_POST['return_cost'],';'));              //运费
        $single_price_arr= explode(';',rtrim($_POST['single_price'],';'));             //单价
        $bad_id_arr      = explode(';',rtrim($_POST['bad_id'],';'));                   //不良品出库单id

        $deal_data = array();
        for($i=0;$i<count($quantity_arr);$i++){
            $send_arr = array(
                'id'                 => $bad_id_arr[$i],
                'purchaseorder_id'   => trim($_POST['purchaseorder_id']),
                'sku'                => trim($_POST['sku']),
                'operate_man'        => $_SESSION['current_account']['id'],
                'unqualified_id'     => trim($_POST['id']),
                'sku_name'           => trim($_POST['sku_name']),
                'deal_time'          => $this->time,
                'check_detail_id'    => trim($_POST['check_detail_id']),
                'store'              => trim($_POST['store']),
                'purchase_man'       => $purchase_man,
                'status'             => 10,
                'quantity'           => $quantity_arr[$i],
                'fail_deal_way'      => $way_arr[$i],
                'unqualified_reason' => $remark_arr[$i],
                'return_cost'        => $return_cost_arr[$i],
                'coupon_price'       => $single_price_arr[$i],
            );
            $deal_data[] = $send_arr;
        }
        return $this->save_deal($deal_data);
    }

    /**
     * 更新不良品出库单打印状态
     * khq 2017.3.17
     */
    public function print_quality() {
        $detail = $this->bad_products_detail($_GET,false);  //不良品信息
        $pur_evidence = $detail[0]['pur_evidence'];
        $evidence = '';
        if(empty($pur_evidence)) {
            $maxid = $this->badProducts->get_max_pur_evidence();
            $time = date('Ymd',time());
            if(empty($maxid)) {
                $evidence = $time.'0001';
            } else {
                $time1 = substr($maxid,0,8);
                $int = substr($maxid,-4);
                if($time == $time1) {
                    $int = $int + 1;
                    $len = '';
                    for($i = strlen($int);$i <4 ;$i++){
                        $len .= '0';
                    }
                    $evidence = $time.$len.$int;
                } else {
                    $evidence = $time.'0001';
                }

            }
        } else {
            $evidence=$pur_evidence;
        }
        $this->badProducts->update(array(
            'id'=>trim($_GET['id'])),array('print_status'=>1,'pur_evidence'=>$evidence));
        $this->badProducts->model->commit();
        return array(
            'result'=>$detail[0],
            'pur_evidence' => $evidence
            );
    }

    /**
     * @param $deal_data
     * @return int
     * 更新不良品出库单数据
     * khq 2017.3.7
     */
    public function save_deal($deal_data)
    {
        try{
            foreach ($deal_data as $K=>$v){
                if($v['id']!=0 && $v['id']){
                    $map['id'] = $v['id'];
                    $this->badProducts->update($map,$v);
                    unset($deal_data[$K]);
                }elseif ($v['id']==0 || $v['id']==''){
                    unset($deal_data[$K]['id']);
                }
            }
            if(!empty($deal_data)){
                $this->badProducts->batch_create(array_values($deal_data));
            }
            $this->badProducts->model->commit();
            return 200;
        }catch (Exception $e){
            $this->badProducts->mode->rollback();
            return 404;
        }
    }
    public function test()
    {
        $_array = array('wms_bad_product_delivery.sku'=>'ZC497100');
        $model = $this->badProducts->bad_products_and_check_detail_model($_array);
        var_dump($model);exit;
        $arr = $model->select();
        return $model->getLastSql();
    }
    public function create($_array = array(),&$model = NULL)
    {
    }

    public function update($_array = array(),$_param= array(),&$model = NULL)
    {

    }
    public function delete()
    {

    }

}